package com.lagou.server;

import com.lagou.UserService;
import com.lagou.handler.UserServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class UserServerImpl implements UserService {
  public String sayHello(String word) {
    System.out.println("调用成功--参数：" + word);
    return "调用成功--参数：" + word;
  }

  public static void startServer(String hostName, int port) {
    try {
      EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
      ServerBootstrap serverBootstrap = new ServerBootstrap();
      serverBootstrap
          .group(eventLoopGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                  ChannelPipeline pipeline = socketChannel.pipeline();
                  pipeline.addLast(new StringEncoder());
                  pipeline.addLast(new StringDecoder());
                  pipeline.addLast(new UserServerHandler());
                }
              });
      serverBootstrap.bind(hostName, port).sync();
      System.out.println("server start!");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
